# -*- coding: utf-8 -*-
"""
HaaS506 RTU TTL模块
简化版本 - TTL串口配置接口
"""

import ujson as json
import utime
from driver import UART
import rtu_config
import rtu_gpio
import rtu_dispatch

# TTL串口
_uart = None
_command_buffer = ""

# 配置模式状态
_config_mode = False
_last_ttl_activity = 0
_config_mode_timeout = 60  # 60秒无活动自动退出配置模式
_ttl_connected = False
_connection_check_interval = 5  # 5秒检查一次连接状态
_last_heartbeat_sent = 0  # 上次发送心跳的时间

def init():
    """初始化TTL模块"""
    global _uart
    
    try:
        _uart = UART()
        _uart.open("TTL")
        print("[TTL] TTL interface initialized")
        return True
    except Exception as e:
        print("[TTL] Init error: {}".format(e))
        return False

def process_commands():
    """处理TTL命令"""
    global _command_buffer, _last_ttl_activity, _ttl_connected, _config_mode
    
    if not _uart:
        return False
    
    try:
        # 读取数据
        buffer = bytearray(256)
        bytes_received = _uart.read(buffer)
        
        if bytes_received > 0:
            # 检测到TTL活动
            _last_ttl_activity = utime.time()
            
            # 如果之前未连接，现在检测到数据，说明TTL已连接
            if not _ttl_connected:
                _ttl_connected = True
                _enter_config_mode()
            
            # 只取实际接收到的数据
            data = buffer[:bytes_received]
            
            # 添加到缓冲区
            _command_buffer += data.decode('utf-8')
            
            # 查找完整的命令（以换行符结尾）
            while '\n' in _command_buffer:
                line, _command_buffer = _command_buffer.split('\n', 1)
                line = line.strip()
                
                if line:
                    _handle_command(line)
        else:
            # 没有数据，检查是否需要退出配置模式
            _check_ttl_timeout()
        
        return True
        
    except Exception as e:
        print("[TTL] Command processing error: {}".format(e))
        return False

def _handle_command(command_str):
    """处理单个命令"""
    try:
        # 使用统一的命令调度器处理TTL命令
        result = rtu_dispatch.process_ttl_command(command_str)
        _send_response(result)
            
    except Exception as e:
        _send_response({"status": "error", "message": "Command error: {}".format(e)})


def _send_response(response):
    """发送响应"""
    if not _uart:
        return
    
    try:
        response_str = json.dumps(response) + '\r\n'
        _uart.write(response_str.encode('utf-8'))
    except Exception as e:
        print("[TTL] Send response error: {}".format(e))

def _enter_config_mode():
    """进入配置模式"""
    global _config_mode
    
    if not _config_mode:
        _config_mode = True
        print("[TTL] =================================")
        print("[TTL] ENTERING CONFIGURATION MODE")
        print("[TTL] TTL connection detected")
        print("[TTL] System operations are now suspended")
        print("[TTL] =================================")
        
        # 发送欢迎消息到TTL
        _send_response({
            "status": "config_mode_enabled",
            "message": "Configuration mode activated. System operations suspended.",
            "timeout": _config_mode_timeout
        })
        
        # 设置LED指示配置模式
        try:
            import rtu_gpio
            rtu_gpio.set_state_led_mode("fast_blink")  # 快闪表示配置模式
        except:
            pass


def _exit_config_mode():
    """退出配置模式"""
    global _config_mode, _ttl_connected
    
    if _config_mode:
        _config_mode = False
        _ttl_connected = False
        print("[TTL] =================================")
        print("[TTL] EXITING CONFIGURATION MODE")
        print("[TTL] Resuming normal system operations")
        print("[TTL] =================================")
        
        # 恢复LED状态
        try:
            import rtu_gpio
            rtu_gpio.set_state_led_mode("slow_blink")  # 恢复正常闪烁
        except:
            pass


def _check_ttl_timeout():
    """检查TTL超时"""
    global _last_ttl_activity, _ttl_connected
    
    if not _ttl_connected:
        return
    
    current_time = utime.time()
    
    # 检查是否超过超时时间
    if current_time - _last_ttl_activity > _config_mode_timeout:
        print("[TTL] No activity for {} seconds, exiting config mode".format(_config_mode_timeout))
        _exit_config_mode()


def is_config_mode():
    """检查是否处于配置模式"""
    return _config_mode


def send_config_mode_status():
    """在配置模式下定期发送状态"""
    global _last_heartbeat_sent
    
    if not _config_mode:
        return
    
    current_time = utime.time()
    
    # 每5秒发送一次状态
    if current_time - _last_heartbeat_sent >= 5:
        _last_heartbeat_sent = current_time
        
        # 构建状态信息
        status = {
            "mode": "config",
            "device_sn": rtu_config.get_device_sn(),
            "version": rtu_config.get_config("system.version", "unknown"),
            "uptime": current_time,
            "config_timeout_remaining": max(0, _config_mode_timeout - (current_time - _last_ttl_activity))
        }
        
        _send_response(status)


def test_ttl():
    """测试TTL接口"""
    print("[TTL] Testing TTL interface...")
    
    # 模拟命令测试
    test_commands = [
        '{"action":"get","key":"device_sn"}',
        '{"action":"status"}',
        '{"action":"list"}'
    ]
    
    for cmd in test_commands:
        print("[TTL] Test command: {}".format(cmd))
        _handle_command(cmd)
    
    print("[TTL] TTL test completed")